-
Notifications
You must be signed in to change notification settings - Fork 1
upd #118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
upd #118
Conversation
|
Caution Review failedThe pull request is closed. WalkthroughAdds many new explanation markdowns and Python solution implementations for assorted algorithm problems (linked lists, trees, graphs, greedy, backtracking, matrix/string utilities), plus updates to data/leetcode-problems.json that replace one entry and append two new problem entries. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (35)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Reviewer's GuideAdds multiple LeetCode problem solutions in Python along with detailed English explanations for some of them, implementing standard algorithmic approaches for arrays, graphs, linked lists, trees, and greedy/DP-style problems. Class diagram for FindElements binary tree recoveryclassDiagram
class TreeNode {
+int val
+TreeNode left
+TreeNode right
}
class FindElements {
-set values
+FindElements(root: TreeNode)
+recover(node: TreeNode, val: int)
+find(target: int) bool
}
FindElements --> TreeNode : uses
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hey there - I've reviewed your changes - here's some feedback:
- In
solutions/2482/01.py,zeros_rowandzeros_colare recomputed inside the innermost loop for every cell; consider precomputingzeros_rowandzeros_colarrays once after counting ones and then reusing them in the result-building loop to avoid redundant work. - In
explanations/2482/en.md, the constraint bullet "matrix can have up to 10^5 rows and columns, with total cells up to 10^5" is internally inconsistent; it would be clearer to state thatmandnare up to 10^5 with the productm * nbounded by 10^5. - In
solutions/1630/01.py, you can avoid sorting for trivial subarrays by checkinglen(subarray) < 2before callingsubarray.sort(), which slightly reduces unnecessary work for very small ranges.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- In `solutions/2482/01.py`, `zeros_row` and `zeros_col` are recomputed inside the innermost loop for every cell; consider precomputing `zeros_row` and `zeros_col` arrays once after counting ones and then reusing them in the result-building loop to avoid redundant work.
- In `explanations/2482/en.md`, the constraint bullet "matrix can have up to 10^5 rows and columns, with total cells up to 10^5" is internally inconsistent; it would be clearer to state that `m` and `n` are up to 10^5 with the product `m * n` bounded by 10^5.
- In `solutions/1630/01.py`, you can avoid sorting for trivial subarrays by checking `len(subarray) < 2` before calling `subarray.sort()`, which slightly reduces unnecessary work for very small ranges.
## Individual Comments
### Comment 1
<location> `solutions/2482/01.py:19-21` </location>
<code_context>
+ res = [[0] * n for _ in range(m)]
+ for i in range(m):
+ for j in range(n):
+ zeros_row = n - ones_row[i]
+ zeros_col = m - ones_col[j]
+ res[i][j] = ones_row[i] + ones_col[j] - zeros_row - zeros_col
+
+ return res
</code_context>
<issue_to_address>
**suggestion (performance):** Avoid recomputing zeros_row/zeros_col inside the inner loop
Since `zeros_row` depends only on `i` and `zeros_col` only on `j`, avoid recomputing them for every cell. Either precompute per-row/per-column arrays, or use the equivalent formula:
```python
res[i][j] = 2 * ones_row[i] - n + 2 * ones_col[j] - m
```
This removes the extra subtractions and repeated work in the inner loop.
</issue_to_address>
### Comment 2
<location> `explanations/2482/en.md:14` </location>
<code_context>
+- **Input Size:** The matrix can have up to 10^5 rows and columns, with total cells up to 10^5.
+- **Time Complexity:** O(m*n) - We need to traverse the matrix twice: once to count ones in rows and columns, and once to build the result matrix.
+- **Space Complexity:** O(m + n) - We store arrays for row and column counts.
+- **Edge Case:** Empty matrix or single cell matrix are handled naturally by the algorithm.
+
+**1.2 High-level approach**
</code_context>
<issue_to_address>
**issue (typo):** Fix subject-verb agreement and phrasing in the edge case sentence.
You could rephrase to: "**Edge Case:** An empty matrix or a single-cell matrix is handled naturally by the algorithm." or "**Edge Case:** Empty or single-cell matrices are handled naturally by the algorithm."
```suggestion
- **Edge Case:** Empty or single-cell matrices are handled naturally by the algorithm.
```
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 11
🧹 Nitpick comments (6)
solutions/1347/01.py (1)
1-13: CorrectminStepslogic; consider movingCounterimport to module scopeThe counting logic is correct and efficiently computes the minimal number of replacements.
For style/readability, you might move the import to the top of the file:
+from collections import Counter + class Solution: def minSteps(self, s: str, t: str) -> int: - from collections import Counter - count_s = Counter(s) count_t = Counter(t)solutions/237/01.py (1)
1-17: Deletion logic is correct under LeetCode constraintsThe copy-and-bypass approach is correct assuming
node.nextis notNone(as per the original problem). If you ever reuse this outside that context, consider adding an assertion or guard aroundnode/node.nextto fail fast on invalid input.explanations/237/en.md (2)
5-28: Consider using proper markdown headings for better structure.The document uses bold text for subsection headers (e.g., Restate the problem, 1.1 Constraints & Complexity) instead of proper markdown headings. This affects document navigation and accessibility.
Apply this diff to use proper heading levels:
-**Restate the problem** +#### Restate the problem -**1.1 Constraints & Complexity** +#### 1.1 Constraints & Complexity -**1.2 High-level approach** +#### 1.2 High-level approach -**1.3 Brute force vs. optimized strategy** +#### 1.3 Brute force vs. optimized strategy -**1.4 Decomposition** +#### 1.4 Decomposition
35-60: Consider using proper markdown headings for the Steps section.Similar to the Strategy section, the Steps subsections use bold text instead of proper markdown headings.
Apply this diff:
-**2.1 Initialization & Example Setup** +#### 2.1 Initialization & Example Setup -**2.2 Start Processing** +#### 2.2 Start Processing -**2.3 Trace Walkthrough** +#### 2.3 Trace Walkthrough -**2.4 Update Pointers** +#### 2.4 Update Pointers -**2.5 Return Result** +#### 2.5 Return Resultsolutions/1079/01.py (1)
3-3: Consider moving import to module level.Importing
Counterinside the method works but is unconventional. Module-level imports are more idiomatic and improve readability.Apply this diff to move the import:
+from collections import Counter + class Solution: def numTilePossibilities(self, tiles: str) -> int: - from collections import Counter - def backtrack(count):explanations/2482/en.md (1)
5-75: Minor doc polish: hyphenation and heading style (optional)The explanation is clear and technically accurate; only small style tweaks are suggested:
- On Line 14, LanguageTool is right that “single cell matrix” should be hyphenated:
-- **Edge Case:** Empty matrix or single cell matrix are handled naturally by the algorithm. +- **Edge Case:** Empty matrix or single-cell matrix are handled naturally by the algorithm.
- markdownlint’s MD036 warnings come from using bold text as section labels (e.g.,
**Restate the problem**,**1.1 Constraints & Complexity**). If you want to satisfy the linter, you can convert these to proper headings, for example:-**Restate the problem** +#### Restate the problemand similarly for the other bolded “section titles” (
**1.1 Constraints & Complexity**,**1.2 High-level approach**, etc.).These are cosmetic and can be applied whenever you next touch the doc.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
explanations/237/en.md(1 hunks)explanations/2482/en.md(1 hunks)explanations/797/en.md(1 hunks)solutions/1008/01.py(1 hunks)solutions/1079/01.py(1 hunks)solutions/1261/01.py(1 hunks)solutions/1326/01.py(1 hunks)solutions/1347/01.py(1 hunks)solutions/1551/01.py(1 hunks)solutions/1605/01.py(1 hunks)solutions/1630/01.py(1 hunks)solutions/1823/01.py(1 hunks)solutions/2120/01.py(1 hunks)solutions/2221/01.py(1 hunks)solutions/2326/01.py(1 hunks)solutions/237/01.py(1 hunks)solutions/2482/01.py(1 hunks)solutions/2637/01.py(1 hunks)solutions/2785/01.py(1 hunks)solutions/797/01.py(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
solutions/1551/01.py (1)
solutions/509/01.py (1)
fib(2-15)
solutions/1347/01.py (1)
solutions/1079/01.py (1)
Solution(1-16)
🪛 LanguageTool
explanations/237/en.md
[style] ~7-~7: Try using a synonym here to strengthen your writing.
Context: ...ode from a linked list, but we are only given access to the node to be deleted (not t...
(GIVE_PROVIDE)
explanations/2482/en.md
[grammar] ~14-~14: Use a hyphen to join words.
Context: ... - Edge Case: Empty matrix or single cell matrix are handled naturally by the...
(QB_NEW_EN_HYPHEN)
🪛 markdownlint-cli2 (0.18.1)
explanations/237/en.md
5-5: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
9-9: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
16-16: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
22-22: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
28-28: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
38-38: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
46-46: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
50-50: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
explanations/2482/en.md
5-5: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
9-9: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
16-16: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
22-22: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
28-28: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
38-38: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
46-46: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
50-50: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
62-62: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
66-66: Emphasis used instead of a heading
(MD036, no-emphasis-as-heading)
🪛 Ruff (0.14.8)
solutions/2637/01.py
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
solutions/1008/01.py
8-8: Undefined name List
(F821)
8-8: Undefined name Optional
(F821)
8-8: Undefined name TreeNode
(F821)
12-12: Undefined name TreeNode
(F821)
16-16: Undefined name TreeNode
(F821)
solutions/2120/01.py
2-2: Undefined name List
(F821)
solutions/2326/01.py
7-7: Undefined name Optional
(F821)
7-7: Undefined name ListNode
(F821)
7-7: Undefined name List
(F821)
7-7: Undefined name List
(F821)
solutions/1605/01.py
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
solutions/2482/01.py
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
solutions/2221/01.py
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
solutions/1326/01.py
2-2: Undefined name List
(F821)
solutions/797/01.py
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
2-2: Undefined name List
(F821)
solutions/1630/01.py
3-3: Undefined name List
(F821)
3-3: Ambiguous variable name: l
(E741)
3-3: Undefined name List
(F821)
3-3: Undefined name List
(F821)
4-4: Undefined name List
(F821)
solutions/1261/01.py
9-9: Undefined name Optional
(F821)
9-9: Undefined name TreeNode
(F821)
🔇 Additional comments (12)
solutions/1823/01.py (1)
1-8: Correct and efficient Josephus implementationThe iterative 0‑indexed recurrence and final
+ 1conversion are correct, handle edge cases liken = 1cleanly, and run in O(n) time / O(1) space. Looks good as a LeetCode solution.solutions/1261/01.py (1)
7-23:FindElementsrecovery + lookup logic looks solidDFS recovery with
root = 0,left = 2*val+1,right = 2*val+2and caching all values in a set gives O(n) preprocessing and O(1)find, and safely handlesroot is None. No issues with the core algorithm.solutions/2785/01.py (1)
1-19: Vowel-sorting implementation is correct and cleanThe algorithm correctly preserves consonant positions, sorts vowels (both cases), and reconstructs the string in a single pass; no issues spotted.
explanations/797/en.md (1)
1-68: DFS/backtracking explanation is clear and aligned with the typical solutionThe write-up accurately restates the problem, matches the DFS + backtracking approach, and the example trace table clearly illustrates how all paths are enumerated.
solutions/1551/01.py (1)
1-17: Greedy Fibonacci decomposition is correct and efficientGenerating Fibonacci numbers up to
kand then greedily subtracting the largest not exceeding the remainder is the right approach here; the implementation is clean and handles edge cases likek = 1correctly.solutions/1605/01.py (1)
6-12: LGTM! Greedy approach is correct.The greedy algorithm correctly distributes values by taking the minimum of remaining row and column sums at each step, ensuring both constraints are satisfied.
solutions/2221/01.py (1)
6-13: LGTM! Champion detection logic is sound.The algorithm correctly identifies a team that beats all others by checking for a row with all 1s except the diagonal.
solutions/1079/01.py (1)
5-13: LGTM! Backtracking logic is correct.The algorithm correctly generates all distinct non-empty sequences by decrementing available counts, recursing, and backtracking.
solutions/1008/01.py (1)
15-27: LGTM! Stack-based BST construction is correct.The iterative approach correctly constructs a BST by maintaining a stack of potential parents and attaching nodes based on BST properties.
solutions/1630/01.py (1)
7-23: LGTM! Arithmetic progression check is correct.The algorithm correctly extracts each subarray, sorts it, and verifies that consecutive differences are constant.
solutions/2326/01.py (1)
16-38: LGTM! Spiral traversal logic is correct.The algorithm correctly fills the matrix in spiral order by tracking direction and changing course when hitting boundaries or already-filled cells.
solutions/1326/01.py (1)
3-32: LGTM! Greedy interval covering is correct.The algorithm correctly converts tap ranges to intervals and uses a greedy approach to find the minimum number of taps needed to cover [0, n].
| # Definition for a binary tree node. | ||
| # class TreeNode: | ||
| # def __init__(self, val=0, left=None, right=None): | ||
| # self.val = val | ||
| # self.left = left | ||
| # self.right = right |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
cat -n solutions/1261/01.pyRepository: romankurnovskii/leetcode-apps
Length of output: 1020
Add missing Optional import and define or quote TreeNode type
Line 9 references Optional[TreeNode], but neither is available: Optional is not imported, and TreeNode is only in comments. This will break at import time and trigger Ruff F821.
For a standalone environment, define the node class and import Optional:
+from typing import Optional
+
# Definition for a binary tree node.
-# class TreeNode:
-# def __init__(self, val=0, left=None, right=None):
-# self.val = val
-# self.left = left
-# self.right = right
+class TreeNode:
+ def __init__(self, val=0, left=None, right=None):
+ self.val = val
+ self.left = left
+ self.right = rightIf this file is meant only for LeetCode submission where TreeNode is pre-defined, keep it commented but at minimum add from typing import Optional and use a string annotation: root: "Optional[TreeNode]" on line 9.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| # Definition for a binary tree node. | |
| # class TreeNode: | |
| # def __init__(self, val=0, left=None, right=None): | |
| # self.val = val | |
| # self.left = left | |
| # self.right = right | |
| from typing import Optional | |
| # Definition for a binary tree node. | |
| class TreeNode: | |
| def __init__(self, val=0, left=None, right=None): | |
| self.val = val | |
| self.left = left | |
| self.right = right |
🤖 Prompt for AI Agents
In solutions/1261/01.py around lines 1 to 6, the code references
Optional[TreeNode] but Optional is not imported and TreeNode is only in
comments; import Optional from typing and either define the TreeNode class
(uncomment/provide the class definition) or keep LeetCode's TreeNode commented
and change annotations to use a forward-ref string like root:
"Optional[TreeNode]"; ensure you add from typing import Optional at the top and
update any type hints accordingly so the file imports cleanly.
| class Solution: | ||
| def minTaps(self, n: int, ranges: List[int]) -> int: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add missing import for type hints.
The List type hint is used but not imported, which will cause a NameError at runtime if type hints are evaluated.
Apply this diff:
+from typing import List
+
class Solution:
def minTaps(self, n: int, ranges: List[int]) -> int:📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| class Solution: | |
| def minTaps(self, n: int, ranges: List[int]) -> int: | |
| from typing import List | |
| class Solution: | |
| def minTaps(self, n: int, ranges: List[int]) -> int: |
🧰 Tools
🪛 Ruff (0.14.8)
2-2: Undefined name List
(F821)
🤖 Prompt for AI Agents
In solutions/1326/01.py around lines 1 to 2, the type hint List is referenced
but not imported; add the missing import by adding "from typing import List" (or
equivalent) at the top of the file so the List name is defined for the minTaps
method signature.
solutions/1630/01.py
Outdated
| class Solution: | ||
| def checkArithmeticSubarrays( | ||
| self, nums: List[int], l: List[int], r: List[int] | ||
| ) -> List[bool]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add missing import and consider renaming parameter.
Two issues:
- The
Listtype hint is used but not imported (critical). - The parameter name
lis ambiguous per PEP 8 guidelines.
Apply this diff:
+from typing import List
+
class Solution:
def checkArithmeticSubarrays(
- self, nums: List[int], l: List[int], r: List[int]
+ self, nums: List[int], left: List[int], right: List[int]
) -> List[bool]:
res = []
- for i in range(len(l)):
- subarray = nums[l[i] : r[i] + 1]
+ for i in range(len(left)):
+ subarray = nums[left[i] : right[i] + 1]Committable suggestion skipped: line range outside the PR's diff.
🧰 Tools
🪛 Ruff (0.14.8)
3-3: Undefined name List
(F821)
3-3: Ambiguous variable name: l
(E741)
3-3: Undefined name List
(F821)
3-3: Undefined name List
(F821)
4-4: Undefined name List
(F821)
🤖 Prompt for AI Agents
In solutions/1630/01.py around lines 1 to 4, the function uses the type hint
List but the module does not import it and the parameter named "l" is ambiguous;
add "from typing import List" at the top of the file and rename the parameter
"l" to a clearer name such as "left" (update all occurrences in the function
signature and body accordingly) so type checking works and the parameter name
follows PEP 8.
| class Solution: | ||
| def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add missing imports for type hints.
The type hints Optional, ListNode, and List are used but not imported, which will cause NameError at runtime if type hints are evaluated.
Apply this diff:
+from typing import List, Optional
+
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
+
class Solution:
def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]:Note: ListNode is typically defined elsewhere in LeetCode's environment, but ensure it's imported or defined if running outside that context.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| class Solution: | |
| def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: | |
| from typing import List, Optional | |
| # Definition for singly-linked list. | |
| # class ListNode: | |
| # def __init__(self, val=0, next=None): | |
| # self.val = val | |
| # self.next = next | |
| class Solution: | |
| def spiralMatrix(self, m: int, n: int, head: Optional[ListNode]) -> List[List[int]]: |
🧰 Tools
🪛 Ruff (0.14.8)
7-7: Undefined name Optional
(F821)
7-7: Undefined name ListNode
(F821)
7-7: Undefined name List
(F821)
7-7: Undefined name List
(F821)
🤖 Prompt for AI Agents
In solutions/2326/01.py around lines 6 to 7, the function signature uses type
hints Optional, ListNode, and List but those names are not imported; update the
file to import the missing typing symbols (e.g. from typing import Optional,
List) and ensure ListNode is available in this module (either import or define a
stub/class matching LeetCode's ListNode) so the annotations do not raise
NameError when evaluated.
Summary by Sourcery
Add multiple new LeetCode-style problem solutions and accompanying explanations for selected problems.
New Features:
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.